package tote.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import tote.web.util.ExposablePropertyPaceholderConfigurer;

/**
 * http://j2eecookbook.blogspot.com/2007/07/accessing-properties-loaded-via-spring.html
 * Listener that exposes properties configured by {@link ExposablePropertyPaceholderConfigurer} to
 * the web application context.
 * More details about usage here http://wiki.sonopia.com/x/GmQ
 * 
 * @author Mykola Palienko
 */
public class ConfigPropertiesExposerListener implements ServletContextListener {

    public static final String DEFAULT_PROPERTIES_BEAN_NAME = "propertyConfigurer";

    public static final String DEFAULT_CONTEXT_PROPERTY = "configProperties";

    private String propertiesBeanName = DEFAULT_PROPERTIES_BEAN_NAME;

    private String contextProperty = DEFAULT_CONTEXT_PROPERTY;

    public void contextDestroyed(ServletContextEvent sce) {
    }

    public void contextInitialized(ServletContextEvent sce) {
	// TODO add ability to configure non default values via serveltContexParams
	ServletContext servletContext = sce.getServletContext();
	WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
	ExposablePropertyPaceholderConfigurer configurer = (ExposablePropertyPaceholderConfigurer) context
		.getBean(propertiesBeanName);
	sce.getServletContext().setAttribute(contextProperty, configurer.getResolvedProps());

    }
}